<script setup>
	import { ref } from 'vue'
	import { useRoleStore } from '@/stores/role'
	import { updatePasswordService } from '@/api/user'
	import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'

	const roleStore = useRoleStore()
	const formLabelAlign = ref({
		old_pwd: '',
		new_pwd: '',
		re_pwd: '',
	})

	const checkRePassword = (rule, value, callback) => {
		if (value === '') {
			callback(new Error('请确认密码'))
		} else if (value !== formLabelAlign.value.new_pwd) {
			callback(new Error('两次密码不一致'))
		} else {
			callback()
		}
	}
	const rules = {
		old_pwd: [
			{
				required: true,
				message: '请输入密码',
				trigger: 'blur',
			},
			{
				min: 5,
				max: 16,
				message: '5-16位非空字符',
				trigger: 'blur',
			},
		],
		new_pwd: [
			{
				required: true,
				message: '请输入新密码',
				trigger: 'blur',
			},
			{
				min: 5,
				max: 16,
				message: '5-16位非空字符',
				trigger: 'blur',
			},
		],
		re_pwd: [
			{
				validator: checkRePassword,
				trigger: 'blur',
			},
		],
	}
	const clear = () => {
		formLabelAlign.value.old_pwd = ''
		formLabelAlign.value.new_pwd = ''
		formLabelAlign.value.re_pwd = ''
	}

	const submit = () => {
		ElMessageBox.confirm(`确认修改密码?`)
			.then(async () => {
				await updatePasswordService(formLabelAlign.value)
				ElNotification({
					title: '修改成功',
					message: `成功修改密码`,
					type: 'success',
				})
				clear()
			})
			.catch(() => {
				ElMessage.info('取消')
				clear()
			})
	}
</script>

<template>
	<el-form
		label-position="right"
		label-width="auto"
		:model="formLabelAlign"
		:rules="rules"
		style="max-width: 600px">
		<el-form-item label="用户名" prop="userName">
			<el-input v-model="roleStore.info.userName" disabled />
		</el-form-item>
		<el-form-item label="密码" prop="old_pwd">
			<el-input v-model="formLabelAlign.old_pwd" />
		</el-form-item>
		<el-form-item label="新密码" prop="new_pwd">
			<el-input v-model="formLabelAlign.new_pwd" />
		</el-form-item>
		<el-form-item label="重新输入密码" prop="re_pwd">
			<el-input v-model="formLabelAlign.re_pwd" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submit">提交修改</el-button>
		</el-form-item>
	</el-form>
</template>

<style scoped></style>
